<template>
  <div class="online-user">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="登录地址" prop="ipaddr">
          <el-input
            v-model="queryForm.ipaddr"
            placeholder="请输入登录地址"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryForm.userName"
            placeholder="请输入用户名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon class="icon-primary"><user /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">在线用户</div>
              <div class="stats-value">{{ onlineStats.total || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon class="icon-success"><calendar /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">今日登录</div>
              <div class="stats-value">{{ onlineStats.today || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="left-operations">
          <el-button
            v-permission="['monitor:online:forceLogout']"
            type="danger"
            icon="Delete"
            :disabled="multiple"
            @click="handleForceLogout"
          >
            强制退出
          </el-button>
          <el-button
            v-permission="['monitor:online:list']"
            type="warning"
            icon="Download"
            @click="handleExport"
          >
            导出
          </el-button>
        </div>
        <div class="right-operations">
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            @change="toggleAutoRefresh"
          />
          <el-tooltip content="刷新" placement="top">
            <el-button icon="Refresh" circle @click="getList" />
          </el-tooltip>
        </div>
      </div>

      <!-- 在线用户列表 -->
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column
          label="用户名称"
          prop="userName"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          label="部门名称"
          prop="deptName"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          label="登录地址"
          prop="ipaddr"
          show-overflow-tooltip
          width="130"
        />
        <el-table-column
          label="登录地点"
          prop="loginLocation"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          label="浏览器"
          prop="browser"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          label="操作系统"
          prop="os"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          label="登录时间"
          prop="loginTime"
          width="160"
        />
        <el-table-column
          label="过期时间"
          prop="expireTime"
          width="120"
        >
          <template #default="{ row }">
            <span>{{ formatExpireTime(row.expireTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template #default="{ row }">
            <el-tooltip content="强制退出" placement="top">
              <el-button
                v-permission="['monitor:online:forceLogout']"
                link
                type="danger"
                icon="Delete"
                @click="handleForceLogout(row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  getOnlineList,
  getOnlineStats,
  forceLogout,
  batchForceLogout,
} from '@/api/monitor/online'
import Pagination from '@/components/Pagination/index.vue'

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref<string[]>([])
// 非多个禁用
const multiple = ref(true)
// 总条数
const total = ref(0)
// 在线用户表格数据
const userList = ref<any[]>([])
// 自动刷新
const autoRefresh = ref(false)
// 在线统计
const onlineStats = reactive<any>({})
let refreshTimer: NodeJS.Timeout | null = null

// 表单引用
const queryFormRef = ref<FormInstance>()

// 查询参数
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  ipaddr: '',
  userName: '',
})

/** 查询在线用户列表 */
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getOnlineList(queryForm)
    userList.value = data.rows || data
    total.value = data.total || (Array.isArray(data) ? data.length : 0)
  } catch (error) {
    console.error('获取在线用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 获取在线统计 */
const getStats = async () => {
  try {
    const { data } = await getOnlineStats()
    Object.assign(onlineStats, data)
  } catch (error) {
    console.error('获取在线统计失败:', error)
  }
}

/** 获取所有信息 */
const getAllInfo = async () => {
  await Promise.all([getList(), getStats()])
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryForm.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.tokenId)
  multiple.value = !selection.length
}

/** 强制退出按钮操作 */
const handleForceLogout = async (row?: any) => {
  const tokenIds = row?.tokenId ? [row.tokenId] : ids.value
  const userNames = row?.userName ? [row.userName] : 
    userList.value.filter(user => tokenIds.includes(user.tokenId)).map(user => user.userName)
  
  try {
    await ElMessageBox.confirm(
      `确认强制退出用户"${userNames.join(', ')}"？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    if (row?.tokenId) {
      await forceLogout(row.tokenId)
    } else {
      await batchForceLogout(tokenIds.join(','))
    }
    
    ElMessage.success('强制退出成功')
    await getAllInfo()
  } catch (error) {
    console.log('取消强制退出')
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await ElMessageBox.confirm('是否确认导出在线用户数据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    // TODO: 实现导出功能
    ElMessage.info('导出功能待实现')
  } catch (error) {
    console.log('取消导出')
  }
}

/** 切换自动刷新 */
const toggleAutoRefresh = (value: boolean) => {
  if (value) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

/** 开始自动刷新 */
const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    getAllInfo()
  }, 30000) // 每30秒刷新一次
}

/** 停止自动刷新 */
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

/** 格式化过期时间 */
const formatExpireTime = (expireTime: number) => {
  if (!expireTime || expireTime <= 0) return '已过期'
  
  const hours = Math.floor(expireTime / 3600)
  const minutes = Math.floor((expireTime % 3600) / 60)
  const seconds = expireTime % 60
  
  if (hours > 0) {
    return `${hours}时${minutes}分`
  } else if (minutes > 0) {
    return `${minutes}分${seconds}秒`
  } else {
    return `${seconds}秒`
  }
}

// 生命周期
onMounted(() => {
  getAllInfo()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style lang="scss" scoped>
.online-user {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-card {
  margin-bottom: 20px;
  
  .stats-content {
    display: flex;
    align-items: center;
    
    .stats-icon {
      margin-right: 16px;
      
      .icon-primary {
        font-size: 40px;
        color: var(--el-color-primary);
      }
      
      .icon-success {
        font-size: 40px;
        color: var(--el-color-success);
      }
    }
    
    .stats-info {
      .stats-title {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin-bottom: 8px;
      }
      
      .stats-value {
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }
  }
}

.operation-card {
  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .left-operations {
      display: flex;
      gap: 8px;
    }
    
    .right-operations {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }
}

:deep(.el-table) {
  .el-table__cell {
    padding: 8px 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .online-user {
    padding: 10px;
  }
  
  .operation-bar {
    flex-direction: column;
    gap: 16px;
    
    .left-operations,
    .right-operations {
      width: 100%;
      justify-content: center;
    }
  }
  
  .stats-card {
    margin-bottom: 10px;
  }
}
</style>

